package com.ruoyi.framework.manager.factory;

import com.alipay.api.response.AlipayFundTransToaccountTransferResponse;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.ip.AddressUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.framework.redis.RedisCache;
import com.ruoyi.project.monitor.domain.SysLogininfor;
import com.ruoyi.project.monitor.domain.SysOperLog;
import com.ruoyi.project.monitor.service.ISysLogininforService;
import com.ruoyi.project.monitor.service.ISysOperLogService;
import com.ruoyi.project.system.domain.*;
import com.ruoyi.project.system.service.*;
import com.ruoyi.project.system.service.impl.SysUserServiceImpl;
import eu.bitwalker.useragentutils.UserAgent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.TimerTask;

import static com.ruoyi.project.system.service.impl.SysQueryPayServiceImpl.paths;

/**
 * 异步工厂（产生任务用）
 *
 * @author ruoyi
 */
public class AsyncFactory {

    private static final Logger sys_user_logger = LoggerFactory.getLogger("sys-user");

    /**
     * 记录登录信息
     *
     * @param username 用户名
     * @param status   状态
     * @param message  消息
     * @param args     列表
     * @return 任务task
     */
    public static TimerTask recordLogininfor(final String username, final String status, final String message, final Object... args) {
        final UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        final String ip = IpUtils.getIpAddr();
        return new TimerTask() {
            @Override
            public void run() {
                String address = AddressUtils.getRealAddressByIP(ip);
                StringBuilder s = new StringBuilder();
                s.append(LogUtils.getBlock(ip));
                s.append(address);
                s.append(LogUtils.getBlock(username));
                s.append(LogUtils.getBlock(status));
                s.append(LogUtils.getBlock(message));
                // 打印信息到日志
                sys_user_logger.info(s.toString(), args);
                // 获取客户端操作系统
                String os = userAgent.getOperatingSystem().getName();
                // 获取客户端浏览器
                String browser = userAgent.getBrowser().getName();
                // 封装对象
                SysLogininfor logininfor = new SysLogininfor();
                logininfor.setUserName(username);
                logininfor.setIpaddr(ip);
                logininfor.setLoginLocation(address);
                logininfor.setBrowser(browser);
                logininfor.setOs(os);
                logininfor.setMsg(message);
                // 日志状态
                if (StringUtils.equalsAny(status, Constants.LOGIN_SUCCESS, Constants.LOGOUT, Constants.REGISTER)) {
                    logininfor.setStatus(Constants.SUCCESS);
                } else if (Constants.LOGIN_FAIL.equals(status)) {
                    logininfor.setStatus(Constants.FAIL);
                }
                // 插入数据
                SpringUtils.getBean(ISysLogininforService.class).insertLogininfor(logininfor);
            }
        };
    }

    /**
     * 操作日志记录
     *
     * @param operLog 操作日志信息
     * @return 任务task
     */
    public static TimerTask recordOper(final SysOperLog operLog) {
        return new TimerTask() {
            @Override
            public void run() {
                // 远程查询操作地点
                operLog.setOperLocation(AddressUtils.getRealAddressByIP(operLog.getOperIp()));
                SpringUtils.getBean(ISysOperLogService.class).insertOperlog(operLog);
            }
        };
    }

    /**
     * 异步转账
     *
     * @param
     * @return 任务task
     */
    public static TimerTask zhuanZhang(final SysExtract sysExtract) {
        return new TimerTask() {
            @Override
            public void run() {
                try {
                    AlipayFundTransToaccountTransferResponse transfer = AlibabaApi.transfer(sysExtract);
                    SysExtract extract;
                    if ("10000".equals(transfer.getCode())) {
                        extract = new SysExtract(transfer.getOutBizNo(), transfer.getOrderId(), transfer.getPayDate(), "已转账");
                        // 公众号通知
                        SysUser sysUser = SpringUtils.getBean(ISysUserService.class).selectUserById(sysExtract.getUserId());
                        if (StringUtils.isNotEmpty(sysUser.getOpenId())) {
                            sysExtract.setTransDate(transfer.getPayDate());
                            TencentApi.pushMessage(sysUser.getOpenId(), sysExtract);
                        }
                    } else {
                        extract = new SysExtract(transfer.getOutBizNo(), "失败");
                        extract.setRemark(transfer.getSubMsg());
                    }
                    SpringUtils.getBean(ISysExtractService.class).updateSysExtract(extract);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
    }

    /**
     * 异步短信通知查询报告
     *
     * @param
     * @return 任务task
     */
    public static TimerTask report(final SysQueryPay sqp) {
        return new TimerTask() {
            @Override
            public void run() {
                try {
                    System.out.println("-------sqp-------" + sqp);
                    // 为上级增加收益
                    String parent = SpringUtils.getBean(SysUserServiceImpl.class).selectUserById(sqp.getUserId()).getParent();
                    if (StringUtils.isNotEmpty(parent)) {
                        SysEarnings sysEarnings = new SysEarnings(Long.parseLong(parent), "other", sqp.getOrderNo(), "您拉新，下级查，我们送！");
                        ISysEarningsService bean = SpringUtils.getBean(ISysEarningsService.class);
                        List<SysEarnings> other = bean.selectSysEarningsList(sysEarnings);
                        if (CollectionUtils.isEmpty(other)) {                                           // 验证为下级新订单
                            String xthb = SpringUtils.getBean(RedisCache.class).getCacheObject("XTHB").toString();
                            sysEarnings.setAmount(BigDecimal.valueOf(Float.parseFloat(xthb)));
                            // 写入红包
                            bean.insertSysEarnings(sysEarnings);
                        }
                    }
                    SysQuery sysQuery = SpringUtils.getBean(ISysQueryService.class).selectSysQueryById(sqp.getQueryId());
                    Integer productId = sysQuery.getProductId();
                    // 建立不动产查询任务
                    if (productId == 6) {
                        SpringUtils.getBean(ISysQueryService.class).addImmovablePropertyQuery(sysQuery);
                    }
                    // 婚恋风险暂不发送报告链接
                    if (productId == 4) {
                        return;
                    }
                    // 向客户发送报告链接短息
                    SpringUtils.getBean(SmSMSService.class).sendReport(sysQuery.getMobile(), paths[productId - 1], sqp.getOrderNo());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
    }
}
